import os
proj_root=os.environ.get('CODE_DIR')+'/frpc_server/'
def get_all_cmd():
    lines=[]
    with open(proj_root+'/src/frpc/rpc_cmd.h',"r") as f:
      lines= f.readlines()
    cmd=[]
    indexes=[0,0]
    index=0
    for l in lines:
        if l.startswith('enum class Command'):
            indexes[0]=index
        elif l.startswith('};//<CMD_END>'):
            indexes[1]=index
            break
        index+=1
    cmd=lines[indexes[0]+1:indexes[1]]
    for i in range(len(cmd)):
        cmd[i]=cmd[i].split('=')[0]
        cmd[i]=cmd[i].split(',')[0]
        cmd[i].strip()
    for i in cmd:
        if i.endswith('Service'):
            cmd.remove(i)
    return cmd
def create_fun_head(cmd):
    lines=[]
    filename=proj_root+'/src/handler/handlers.h'
    with open(filename,"r") as f:
      lines= f.readlines()
    starti=lines.index('{//<START>\n')+1
    endi=lines.index('}//<END>\n')
    startL=lines[0:starti]
    footL=lines[endi:]
    midd=[]
    for i in range(len(cmd)):
        midd.append('void '+cmd[i]+'(Request *, Reply *,void*);\n')
    startL.extend(midd)
    startL.extend(footL)
    with open(filename,"w") as f:
        for line in startL:
            f.write(line)
def create_fun_cpp(cmds):
    lines=[]
    filename=proj_root+'/src/handler/handlers.cpp'
    with open(filename,"r") as f:
      lines= f.readlines()
    cmd_to_create=cmds[:]
    for l in lines:
        for cmd in cmds:
            if cmd in l:
                cmd_to_create.remove(cmd)
    endi=0
    for i in range(len(lines)):
        if '//<END>' in lines[len(lines)-1-i]:
            endi=len(lines)-i
            break
    startL=lines[0:endi]
    footL=lines[endi+1:]
    midd=[]
    for i in range(len(cmd_to_create)):
        midd.append('\n      void '+cmd_to_create[i]+'(Request *req, Reply *rep,void* ctx){\n             rep->set_status_output(Status::NotFound,std::string("Handler not implemented"));\n         }//<END>\n\n')
    startL.extend(midd)
    startL.extend(footL)
    with open(filename,"w") as f:
        for line in startL:
            f.write(line)

def create_router(cmds):
    filename=proj_root+'/src/protocol/frpc_msg.cpp'
    with open(filename,"r") as f:
      lines= f.readlines()
    starti=lines.index('void FrpcRepMsg::init_handler(){\n')
    endi=lines.index('}//<END_INIT_HANDLER>\n')
    startL=lines[0:starti+1]
    footL=lines[endi:]
    midd=[]
    for cmd in cmds:
        midd.append('      router.add_handler(uint32_t(Command::{0}), Frpc::{0});\n'.format(cmd))

    startL.extend(midd)
    startL.extend(footL)
    with open(filename,"w") as f:
        for line in startL:
            f.write(line)
if __name__=='__main__':
    cmds=get_all_cmd()
    create_fun_head(cmds)
    create_fun_cpp(cmds)
    create_router(cmds)